package com.xoa.service.workflow.flowtype.impl;

import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.flowRunFeedback.FlowRunFeedbackMapper;
import com.xoa.dao.template.TemplateModuleMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.*;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.flowxml.FlowOutXml;
import com.xoa.model.flowxml.FlowProcessXml;
import com.xoa.model.flowxml.FlowTypeXml;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.WFE.WFEFactory.WFEFormData;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.users.UsersPrivService;
import com.xoa.service.users.UsersService;
import com.xoa.service.workflow.JobClassifyService;
import com.xoa.service.workflow.flowtype.FlowTypeService;
import com.xoa.service.workflow.wrapper.JobSelectorWrapper;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.PHPSerializerUtils;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.yirong.exchange.model.User;
import org.jdom2.CDATA;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.InputSource;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建作者:   张勇
 * 创建日期:   2017/5/8 16:43
 * 类介绍  :
 * 构造参数:
 */
@Service
public class FlowTypeServiceImpl implements FlowTypeService {

    @Autowired
    private WFELog wfeLog;
    @Resource
    private FlowTypeModelMapper flowTypeModelMapper;
    @Autowired
    JobClassifyService classifyService;
    @Autowired
    FlowProcessMapper processMapper;
    @Autowired
    FlowRunMapper flowRunMapper;
    @Autowired
    FlowRunPrcsMapper flowRunPrcsMapper;

    @Autowired
    FormSortMapper sortMapper;
    @Autowired
    FlowSortMapper flowSortMapper;

    @Autowired
    WorkMapper workMapper;

    @Autowired
    FlowFormTypeMapper flowFormTypeMapper;

    @Autowired
    FlowRunFeedbackMapper flowRunFeedbackMapper;

    @Autowired
    HttpServletRequest request;
    @Autowired
    FlowProcessMapper flowProcessMapper;


    @Resource
    private DepartmentService departmentService;

    @Resource
    private UsersService usersService;

    @Resource
    private UsersPrivService usersPrivService;
    @Resource
    EnclosureService enclosureService;

    @Autowired
    WFEFormData wfeFormData;

    @Autowired
    private TemplateModuleMapper templateModuleMapper;

    @Autowired
    private FlowAssignMapper flowAssignMapper;

    @Autowired
    private FlowPrivMapper flowPrivMapper;
    @Autowired
    private FlowAssociationSetMapper flowAssociationSetMapper;
    @Autowired
    private SysParaMapper sysParaMapper;


    /**
     * @param flowTypeModel
     * @return
     */
    @Override
    @Transactional
    public ToJson<FlowTypeModel> saveFlow(FlowTypeModel flowTypeModel) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        try {
            if (StringUtils.checkNull(flowTypeModel.getAutoNumTime())) {
                flowTypeModel.setAutoNumTime("2000-01-01 00:00:00");
            }
            flowTypeModelMapper.save(flowTypeModel);
            toJson.setMsg("ok");
            toJson.setFlag(0);
            toJson.setObject(flowTypeModel);

            /**    李然  工作流程设计日志添加---新建流程     **/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog = wfeLog.getFlowManageLog(request);
            flowManageLog.setType(Constant.DESIGNTYPE3);
            flowManageLog.setFlowId(flowTypeModel.getFlowId());
            wfeLog.addFlowManageLog(flowManageLog);
        } catch (Exception e) {
            L.e("保存异常：" + e);
            e.printStackTrace();
            toJson.setMsg("error");
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson<FlowTypeModel> selectAllFlow(Integer flowId) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        try {
            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
            if (!StringUtils.checkNull(flowTypeModel.getViewDept())) {
                flowTypeModel.setViewDeptName(departmentService.getDeptNameByDeptId(flowTypeModel.getViewDept(), ","));
            }
            if (!StringUtils.checkNull(flowTypeModel.getViewRole())) {
                flowTypeModel.setViewRoleName(usersPrivService.getPrivNameByPrivId(flowTypeModel.getViewRole(), ","));
            }
            if (!StringUtils.checkNull(flowTypeModel.getViewUser())) {
                flowTypeModel.setViewUserName(usersService.getUserNameById(flowTypeModel.getViewUser()));
            }
//            if(!StringUtils.checkNull(flowTypeModel.getAttachmentId())){
//                Attachment attachment = enclosureService.findByAttachId(Integer.valueOf(flowTypeModel.getAttachmentId()));
//                if(attachment!=null){
//                    String sqlType= "xoa" + (String) request.getSession().getAttribute(
//                            "loginDateSouse");
//                    attachment.setAttUrl("AID="+attachment.getAid()+"&COMPANY="+sqlType+"&YM="+attachment.getYm()+"&ATTACHMENT_ID="+attachment.getAttachId()+"&ATTACHMENT_NAME="+attachment.getAttachName()+"&MODULE="+GetAttachmentListUtil.MODULE_WORKFLOW);
//                }
//                List sss= new ArrayList<Attachment>();
//                sss.add(attachment);
//                flowTypeModel.setAttachment(sss);
//            }
//            flowTypeModel.setAttachment(GetAttachmentListUtil.returnAttachment(flowTypeModel.getAttachmentName(),flowTypeModel.getAttachmentId(),"xoa1001",GetAttachmentListUtil.MODULE_WORKFLOW));
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(flowTypeModel);
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/23 17:31
     * 方法介绍:   自定义属性所有查询，根据flowId
     * 参数说明:
     *
     * @return
     */
    @Override
    public ToJson<FlowTypeModel> selectAllFlow(Integer flowId, HttpServletRequest request) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        try {
            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
            if (!StringUtils.checkNull(flowTypeModel.getViewDept())) {//2020/3/19  传阅人后添加,
                flowTypeModel.setViewDeptName(departmentService.getDeptNameByDeptId(flowTypeModel.getViewDept(), ",") + ",");
            } else {
                flowTypeModel.setViewDeptName("");
            }
            if (!StringUtils.checkNull(flowTypeModel.getViewRole())) {
                flowTypeModel.setViewRoleName(usersPrivService.getPrivNameByPrivId(flowTypeModel.getViewRole(), ",") + ",");
            } else {
                flowTypeModel.setViewRoleName("");
            }
            if (!StringUtils.checkNull(flowTypeModel.getViewUser())) {
                flowTypeModel.setViewUserName(usersService.getUserNameById(flowTypeModel.getViewUser()) + ",");
            } else {
                flowTypeModel.setViewUserName("");
            }
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            String attachmentStrs = flowTypeModel.getAttachmentId();
            String attachmentStrName = flowTypeModel.getAttachmentName();
            List<Attachment> list = null;
            if (!StringUtils.checkNull(attachmentStrs) && !StringUtils.checkNull(attachmentStrName)) {
                list = GetAttachmentListUtil.returnAttachment(attachmentStrName, attachmentStrs, sqlType, GetAttachmentListUtil.MODULE_WORKFLOW);
            }
            flowTypeModel.setAttachment(list);
            org.jsoup.nodes.Document document = wfeFormData.getFormDocument(flowId);
            List<String> list1 = HtmlUtil.getAllDocumentName(document);
            toJson.setObj1(list1);

//            flowTypeModel.setAttachment(GetAttachmentListUtil.returnAttachment(flowTypeModel.getAttachmentName(),flowTypeModel.getAttachmentId(),"xoa1001",GetAttachmentListUtil.MODULE_WORKFLOW));
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(flowTypeModel);
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    @Override
    public ToJson<FlowTypeModel> quertBySortId(Integer flowId, HttpServletRequest request) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        List<FlowTypeModel> datas = flowTypeModelMapper.selectBySortid(flowId);
        if (datas != null && datas.size() > 0) {
            toJson.setObj(datas);
            toJson.setFlag(0);
            toJson.setMsg("success");
        } else {
            toJson.setFlag(1);
            toJson.setMsg("no data");
        }

        return toJson;
    }

    @Override
    public ToJson<FlowTypeModel> flowBySearch(String searchValue, Integer flowId) {

        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        if (StringUtils.checkNull(searchValue)) {
            toJson.setFlag(1);
            toJson.setMsg("搜索字段不能为空");
            return toJson;
        }

        List<FlowTypeModel> datas = flowTypeModelMapper.selectBySearch(searchValue, flowId);
        if (datas != null && datas.size() > 0) {
            toJson.setObj(datas);
            toJson.setFlag(0);
            toJson.setMsg("success");
        } else {
            toJson.setFlag(1);
            toJson.setMsg("no data");
        }
        return toJson;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/23 19:35
     * 方法介绍:   自定义属性根据flowId修改
     * 参数说明:
     *
     * @return
     */
    @SuppressWarnings("all")
    @Override
    @Transactional
    public ToJson<FlowTypeModel> updateFlow(FlowTypeModel flowTypeModel) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        try {
            int a = flowTypeModelMapper.updateFlowTypeModel(flowTypeModel);
            if (a > 0) {
                toJson.setFlag(0);
                toJson.setMsg("ok");
                /**    工作流程设计日志添加---编辑流程     **/
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                FlowManageLog flowManageLog = wfeLog.getFlowManageLog(request);
                flowManageLog.setType(Constant.DESIGNTYPE21);
                flowManageLog.setFlowId(flowTypeModel.getFlowId());
                wfeLog.addFlowManageLog(flowManageLog);
            } else {
                toJson.setFlag(1);
                toJson.setMsg("err");
            }

        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
            L.e("错误消息：" + e);
        }
        return toJson;
    }

    @Override
    public ToJson<FlowTypeModel> selectFlowAuthOrSearch(HttpServletRequest request, String searchValue, Integer sortId) {
        Map<String, Object> param = new HashMap<String, Object>();
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (user.getUid() == null) {
            toJson.setFlag(1);
            toJson.setMsg("无法获取用户信息");
            return toJson;
        }

        List<Integer> sirtIds = classifyService.getSortChildId(sortId, new ArrayList<Integer>());
        StringBuffer sirtIdsTr = new StringBuffer();
        int i = 0;
        for (Integer integer : sirtIds) {
            sirtIdsTr.append(integer);
            if (i != sirtIds.size()) {
                sirtIdsTr.append(",");
            }
            i++;
        }
        Integer[] arry = new Integer[]{};
        arry = sirtIds.toArray(arry);
        String privOther = user.getUserPrivOther() == null ? "" : user.getUserPrivOther();//辅助角色
        String privIds[] = StringUtils.checkNull(privOther) ? null : privOther.split(",");
        String deptOther = user.getDeptIdOther() == null ? "" : user.getDeptIdOther();//辅助部门
        String deptIds[] = StringUtils.checkNull(deptOther) ? null : deptOther.split(",");
        param.put("user", user.getUserId() == null ? "" : user.getUserId());
        param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
        param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());
        if (privIds != null && privIds.length > 0) {
            param.put("privIds", privIds);
        }
        if (deptIds != null && deptIds.length > 0) {
            param.put("deptIds", deptIds);
        }
        param.put("searchValue", searchValue);
        L.w(arry);
        if (sortId != null) {
            param.put("sortId", sirtIdsTr.toString());
        }

        List<FlowTypeModel> datas = flowTypeModelMapper.selectFlowAuthOrSearch(param);
       /* if (user.getUserId() != null && user.getUserId().trim().equals("admin")) {
            datas = flowTypeModelMapper.selectFlowAuthOrSearchAdmin(param);
        }*/

        if (datas != null && datas.size() > 0) {
            toJson.setFlag(0);
            toJson.setMsg("成功");
            toJson.setObj(datas);
        } else {
            toJson.setFlag(1);
            toJson.setMsg("没有数据！");
        }
        return toJson;
    }

    @Override
    public ToJson<FlowDetailInfo> selectFlowDetailInfo(Integer flowId) {
        ToJson<FlowDetailInfo> ret = new ToJson<FlowDetailInfo>();
        if (flowId == null) {
            ret.setFlag(1);
            ret.setMsg("流程Id不能为空");
            return ret;
        }
        FlowDetailInfo info = flowTypeModelMapper.selectFlowDetailInfo(flowId);
        try {
            if (0 != info.getTemplateId()) {
                String templateName = templateModuleMapper.selectByPrimaryKey(info.getTemplateId()).getName();
                info.setTemplateName(templateName);
            }
        } catch (Exception e) {
            e.getStackTrace();
            ret.setMsg(e.getMessage());
        }

        if (!StringUtils.checkNull(info.getAttachmentId())) {//返回的附件信息
            info.setAttachmentList(GetAttachmentListUtil.returnAttachment(info.getAttachmentName(), info.getAttachmentId(), "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_WORKFLOW));
        }
        //断点处理
        List<FlowProcess> datas = processMapper.selectPricByFlowId(flowId);

        //处理是否可回退
        if (info == null) {
            ret.setFlag(1);
            ret.setMsg("没有信息");
        } else {
            int cutNum = cutNumber(datas);
            info.setCutNumber(cutNum);
            ret.setObject(info);
            ret.setFlag(0);
            ret.setMsg("成功");
        }
        return ret;
    }

    private Integer cutNumber(List<FlowProcess> datas) {
        if (datas == null || datas.size() == 0) {
            return 0;
        }
        int res = 0;
        for (int i = 0; i < datas.size() - 1; i++) {
            FlowProcess now = datas.get(i);
            if (StringUtils.checkNull(now.getPrcsTo())) {
                res++;
            } else if ("0,".equals(now.getPrcsTo())) {
                res++;
            }
//            FlowProcess now=datas.get(i);
//            FlowProcess next=datas.get(i+1);
//            if(now.getPrcsId()!=null){
//                if(next.getPrcsId()!=null){
//                    if(now.getPrcsId()+1==next.getPrcsId()){
//                    }else{
//                        res++;
//                    }
//                }else{
//                    res++;
//                }
//            }else{
//                res++;
//            }
        }
        return res;
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/22 10:55
     * 方法介绍:   根据flowId和formId查询一条数据
     * 参数说明:
     *
     * @return
     */
    @Override
    public FlowTypeModel selectOnlyType(Integer flowId, Integer formId) {
        return flowTypeModelMapper.selectOnlyType(flowId, formId);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/7 10:47
     * 方法介绍:   查询说明和附件
     * 参数说明:
     *
     * @return
     */
    @Override
    public ToJson<FlowTypeModel> selectAttachmentAndInstructions(Integer flowId, Integer formId, String sqlType) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>(1, "error");
        try {
            FlowTypeModel flowTypeModel = flowTypeModelMapper.selectAttachmentAndInstructions(flowId, formId);
            if (flowTypeModel.getAttachmentName() != null && flowTypeModel.getAttachmentId() != null) {
                flowTypeModel.setAttachment(GetAttachmentListUtil.returnAttachment(flowTypeModel.getAttachmentName(), flowTypeModel.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_WORKFLOW));
            } else {
                flowTypeModel.setAttachmentName("");
                flowTypeModel.setAttachmentId("");
            }
            toJson.setObject(flowTypeModel);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            L.e("FlowTypeServiceImpl selectAttachmentAndInstructions:" + e);
        }
        return toJson;
    }

    public FlowTypeModel sfTbyrunId(Integer runId) {
        FlowTypeModel flowTypeModel = flowTypeModelMapper.sflowType(runId);
        return flowTypeModel;
    }

    @Override
    public BaseWrapper getFlowOutModel(Integer flowId) throws Exception {
        BaseWrapper wrapper = new BaseWrapper();
        FlowOutXml flowOutXml = new FlowOutXml();
        FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
        FlowTypeXml typeXml = invokeFlowData(flowTypeModel, FlowTypeXml.class);
        List<FlowProcess> datas = processMapper.selectPricByFlowId(flowId);
        List<FlowProcessXml> pro = new ArrayList<FlowProcessXml>();
        for (FlowProcess flowProcess : datas) {
            FlowProcessXml processXml = invokeFlowData(flowProcess, FlowProcessXml.class);
            pro.add(processXml);
        }
        flowOutXml.setProcess(pro);
        flowOutXml.setBaseInfo(typeXml);
        wrapper.setData(writeFileUsingJDOM(flowOutXml));
        wrapper.setMsg(flowTypeModel.getFlowName());
        return wrapper;
    }

    @Override
    public BaseWrapper intputFlowFile(Integer flowId, MultipartFile file) {
        BaseWrapper wrapper = new BaseWrapper();
        try (InputStream inputStream = file.getInputStream()) {
            //clean process with flowId same
            processMapper.deleteByFlowId(flowId);
            readFlowXml(flowId, inputStream);
            wrapper.setFlag(true);

            /**    张晋通 工作流程设计日志添加---导入流程     **/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog = wfeLog.getFlowManageLog(request);
            flowManageLog.setType(Constant.DESIGNTYPE16);
            flowManageLog.setFlowId(flowId);
            wfeLog.addFlowManageLog(flowManageLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public BaseWrapper deleteFlow(Integer flowId) {
        BaseWrapper wrapper = new BaseWrapper();
        wrapper.setStatus(true);
        wrapper.setFlag(false);
        //Clean process with flowId same
        try {
            //获取request 添加日志用
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog = wfeLog.getFlowManageLog(request);
            /* 添加工作流设计日志---删除流程所有数据*/
            flowManageLog.setFlowId(flowId);
            flowManageLog.setType(Constant.DESIGNTYPE12);
            wfeLog.addFlowManageLog(flowManageLog);

            processMapper.deleteByFlowId(flowId);
            flowTypeModelMapper.deleteByFlowId(flowId);
            List<Integer> runIds = flowRunMapper.getRunIdsByFlowId(flowId);
            if (runIds != null && runIds.size() > 0) {
                flowRunMapper.deleteByFlowId(flowId);
                flowRunPrcsMapper.deleteByRunIds(runIds);
                flowAssignMapper.deleteFlowAssign(runIds);
            }
            wrapper.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

        return wrapper;
    }

    @Override
    public BaseWrapper clearFlow(Integer flowId) {
        BaseWrapper wrapper = new BaseWrapper();
        wrapper.setStatus(true);
        wrapper.setFlag(false);
        //Clean process with flowId same
        try {
            //获取request 添加日志用
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog = wfeLog.getFlowManageLog(request);
            /* 添加工作流设计日志---清空*/
            flowManageLog.setFlowId(flowId);
            flowManageLog.setType(Constant.DESIGNTYPE17);
            wfeLog.addFlowManageLog(flowManageLog);
            List<Integer> runIds = flowRunMapper.getRunIdsByFlowId(flowId);
            if (runIds != null && runIds.size() > 0) {
                flowRunPrcsMapper.deleteByRunIds(runIds);
                flowRunMapper.deleteByFlowId(flowId);
                workMapper.truncate("flow_data_" + flowId);
                //删除会签意见
                flowRunFeedbackMapper.delFlowRunFeedBackBylist(runIds);
                flowAssignMapper.deleteFlowAssign(runIds);


            }
            wrapper.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return wrapper;
    }

    private void readFlowXml(Integer flowId, InputStream read) throws Exception {
        SAXBuilder sb = new SAXBuilder();
        InputSource source = new InputSource(read);
        Document doc = sb.build(source);//构造文档对象
        Element root = doc.getRootElement();//获取根元素，即文档中的<HD>
        List baseInfos = root.getChildren("BaseInfo");//取名字为disk的所有元素
        for (Object element : baseInfos) {
            FlowTypeModel flowTypeModel = resolveDatas(element, FlowTypeXml.class, FlowTypeModel.class);
            flowTypeModel.setFlowId(flowId);
            flowTypeModel.setFlowName(null);
            flowTypeModel.setFormId(null);
            flowTypeModel.setFlowSort(null);
            flowTypeModelMapper.updateFlowTypeModel(flowTypeModel);
        }
        List process = root.getChildren("Process");
        for (Object element : process) {
            FlowProcess flowProcess = resolveDatas(element, FlowProcessXml.class, FlowProcess.class);
            flowProcess.setId(null);
            flowProcess.setFlowId(flowId);
            flowProcess.setRelationWorkYn("0");
            flowProcess.setFileuploadPriv(PHPSerializerUtils.unSerializer(flowProcess.getFileuploadPriv()));
            flowProcess.setImguploadPriv(PHPSerializerUtils.unSerializer(flowProcess.getImguploadPriv()));
            processMapper.insert(flowProcess);
        }
        read.close();
    }

    private <T> T resolveDatas(Object data, Class clazz1, Class<T> clazz) throws Exception {
        String checkCulm = "MANAGE_USER,QUERY_USER,NEW_USER,DEPT_ID,PRCS_USER,PRCS_DEPT,PRCS_PRIV,AUTO_USER_OP,AUTO_USER,MAIL_TO";
        T ret = clazz.newInstance();
        Element element = (Element) data;//依此遍历所有的disk节点
        Field[] fields = clazz1.getDeclaredFields();
        //cs导入流程需导入经办人，，添加判断
        String sysPara = null;
        try {
            sysPara = sysParaMapper.querySysPara("MYPROJECT").getParaValue();//防止有的产品没有myproject这个值
        } catch (Exception e) {

        }
        for (Field field : fields) {
            String name = field.getName();
            //cs导入流程需导入经办人，，添加判断
            if (StringUtils.checkNull(sysPara) || !sysPara.equals("powerchina")) {
                if (checkCulm.indexOf(name) > 0) continue;
            }
            String value = element.getChildText(field.getName());
            if (StringUtils.checkNull(value)) continue;
            String caml = StringUtils.underline2Camel(name, true);
            if (caml.length() == 2) {
                caml.toLowerCase();
            }
            Field child = clazz.getDeclaredField(caml);
            child.setAccessible(true);
            field.setAccessible(true);
            Method set_Method = clazz.getMethod("set"
                            + SessionUtils.getMethodName(caml),
                    child.getType());
            Class clazzz = child.getType();
            set_Method.setAccessible(true);
            if (clazzz == String.class) {
                set_Method.invoke(ret, value);
            }
            if (clazzz == Integer.class) {
                set_Method.invoke(ret, Integer.parseInt(value));
            }
            if (clazzz == Byte.class) {
                set_Method.invoke(ret, Byte.parseByte(value));
            }
            if (clazzz == Double.class) {
                set_Method.invoke(ret, Double.parseDouble(value));
            }
            if (clazzz == Float.class) {
                set_Method.invoke(ret, Float.parseFloat(value));
            }
            if (clazzz == Date.class) {
                if (!value.equals("2000-01-01 00:00:00")) {
                    set_Method.invoke(ret, DateFormat.getDate(value));
                }

            }
        }
        return ret;
    }

    //处理映射关系
    private <T> T invokeFlowData(Object object, Class<T> clazz) {
        try {
            T ret = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                String camlStr = null;
                if (name.length() == 2) {
                    camlStr = name.toLowerCase();
                } else {
                    camlStr = StringUtils.underline2Camel(name, true);
                }

                Field child = object.getClass().getDeclaredField(camlStr);
                if (child != null) {
                    child.setAccessible(true);
                    field.setAccessible(true);
                    Method set_Method = clazz.getMethod("set"
                                    + name,
                            field.getType());
                    set_Method.setAccessible(true);
                    set_Method.invoke(ret, child.get(object));
                }
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Document writeFileUsingJDOM(FlowOutXml outXml) throws Exception {
        Document doc = new Document();
        doc.setRootElement(new Element("WorkFlow"));
        if (outXml != null) {
            Element element = new Element("BaseInfo");
            addConet(element, outXml.getBaseInfo());
            doc.getRootElement().addContent(element);
            addConetList(doc, outXml.getProcess());
        }
        return doc;

    }

    private void addConetList(Document doc, List<FlowProcessXml> process) throws Exception {
        for (FlowProcessXml processXml : process) {
            Element element = new Element("Process");
            Field[] fields = processXml.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                CDATA cdata = new CDATA(field.getName()).setText(field.get(processXml) == null ? " " : field.get(processXml).toString());
                element.addContent(new Element(field.getName()).addContent(cdata));
            }
            doc.getRootElement().addContent(element);
        }
    }

    private void addConet(Element element, FlowTypeXml baseInfo) throws Exception {
        Field[] fields = baseInfo.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            CDATA cdata = new CDATA(field.getName()).setText(field.get(baseInfo) == null ? " " : field.get(baseInfo).toString());
            element.addContent(new Element(field.getName()).addContent(cdata));
        }
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2018/1/26 10:47
     * 方法介绍:   查询所有设计流程
     * 参数说明:
     *
     * @return
     */
    @Override
    public ToJson<FlowTypeModel> selAllType() {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>(1, "error");
        try {
            List<FlowTypeModel> flowTypeModelList = flowTypeModelMapper.selAllType();
            toJson.setObj(flowTypeModelList);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            L.e("FlowTypeServiceImpl selAllType:" + e);
        }
        return toJson;
    }

    @Override
    public JobSelectorWrapper selOneToAllType(HttpServletRequest request) {
        JobSelectorWrapper wrapper = new JobSelectorWrapper();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        wrapper.setStatus(true);
        wrapper.setFlag(false);
        //type：空工作流加公文，0工作流，1公文发文，2公文收文
        String type = request.getParameter("type");
        //获取admin所有流程分类
        //List<FlowSort> allDatas = flowSortMapper.selectAllFsDocument(map);
        Map<String, String> map = new HashMap<String, String>();
        map.put("deptId", user.getDeptId().toString());
        map.put("type", type);
        List<FlowSort> allDatas = flowSortMapper.selectAllFsAdmin();
        //获取所有流程分类
        //List<FlowSort> nosortDatas= flowSortMapper.selectAllFlowSort(user.getDeptId());
        if (user.getUserId() != null && "admin".equals(user.getUserId())) {
            allDatas = flowSortMapper.selectAllFsDocumentAdmin();
        }


        for (FlowSort flowSort : allDatas) {
            Integer flowCounts = flowSortMapper.countAllFs(flowSort.getSortId());
            flowSort.setFlowcounts(flowCounts);
        }
        List<FlowSort> authdatasSort = sortDatasAuthFlow(allDatas, 0, allDatas);
        if (authdatasSort != null && authdatasSort.size() > 0) {
            wrapper.setFlag(true);
            wrapper.setMsg("获取成功");
            wrapper.setDatas(authdatasSort);
        } else {
            wrapper.setFlag(false);
            wrapper.setMsg("没有数据");
        }

        return wrapper;
    }

    private List<FlowSort> sortDatasAuthFlow(List<FlowSort> authdatas, Integer sortIda, List<FlowSort> alldata) {
        if (authdatas == null) return null;
        List<FlowSort> datas = new ArrayList<FlowSort>();
        //遍历权限获取
        for (FlowSort sort : authdatas) {
            if (sort != null) {
                //统计符合条件的
                List<FlowSort> authdatass = new ArrayList<FlowSort>();
                //流程分类不是一级分类

                if (sort.getSortParent() != 0) {
                    int checkRes = 0;
                    for (FlowSort need : authdatas) {
                        if (need.getSortId() != sort.getSortParent()) {
                            checkRes++;
                        }
                    }
                    //全部为一级分类
                    if (checkRes == authdatas.size()) {
                        authdatass.addAll(authdatas);
                        for (FlowSort all : alldata) {
                            if (all.getSortId() == sort.getSortParent()) {
                              /*  List<FlowTypeModel> list = flowTypeModelMapper.selectByFlowType(all.getSortId());
                                all.setFlowTypeModels(list);*/
                                authdatass.add(all);
                            }
                        }
                    }
                }
                if (authdatass.size() > 0) {
                    if (sort.getSortParent() == sortIda) {
                        List<FlowTypeModel> list = this.childFlowType(sort.getSortId());
                        sort.setFlowTypeModels(list);
                        sort.setChilds(sortDatasAuthFlow(authdatass, sort.getSortId(), alldata));
                        datas.add(sort);
                    }
                } else {
                    if (sort.getSortParent() == sortIda) {
                        List<FlowTypeModel> list = this.childFlowType(sort.getSortId());
                        sort.setFlowTypeModels(list);
                        sort.setChilds(sortDatasAuthFlow(authdatas, sort.getSortId(), alldata));
                        datas.add(sort);
                    }
                }

            }
        }
        return datas;
    }

    public List<FlowTypeModel> childFlowType(Integer sortId) {
        List<FlowTypeModel> list = flowTypeModelMapper.selectByFlowType(sortId);
        for (FlowTypeModel flowTypeModel : list) {
            FlowDetailInfo info = flowTypeModelMapper.selectFlowDetailInfo(flowTypeModel.getFlowId());
            if (info != null) {
                flowTypeModel.setHandling(info.getRunIngCount() == null ? 0 : info.getRunIngCount());
                flowTypeModel.setEnd(info.getEndRun());
            }
        }
        return list;
    }


    public List<FlowTypeModel> serchChildFlowType(Integer sortId, String sqlType) {
        List<FlowTypeModel> list = flowTypeModelMapper.selectByFlowType(sortId);
        Iterator it = list.iterator();
        Map<String, Object> param = new HashMap<String, Object>();
        if (StringUtils.checkNull(sqlType)) {
            param.put("tableSchema", "xoa1001");
        } else {
            param.put("tableSchema", sqlType);
        }
        while (it.hasNext()) {
            FlowTypeModel flowTypeModel = (FlowTypeModel) it.next();
            param.put("tableName", "flow_data_" + flowTypeModel.getFlowId());
            List<String> columns = workMapper.showColumns(param);
            if (columns.size() == 0) {
                it.remove();
            }
        }
        for (FlowTypeModel flowTypeModel : list) {
            //处理流程于表单关联数据不存在问题，此处可优化，sql改为单独查流程
            try {
                    FlowDetailInfo info = flowTypeModelMapper.selectFlowDetailInfo(flowTypeModel.getFlowId());
                    flowTypeModel.setHandling(info.getRunIngCount());
                    flowTypeModel.setEnd(info.getEndRun());
            } catch (Exception e) {

            }
        }
        return list;
    }


    public AjaxJson selByFlowSort(Integer sortId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            List<FlowTypeModel> list = flowTypeModelMapper.selByFlowSort(sortId);
            ajaxJson.setObj(list);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("true");
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }


    public AjaxJson selFlowSorByAndroid(Map<String, Object> param) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            List<FlowTypeModel> list = null;
            if (param.get("user") != null && param.get("user").toString().trim().equals("admin")) {
                list = flowTypeModelMapper.selFlowSorByAndroidAdmin(param);
            } else {
                list = flowTypeModelMapper.selFlowSorByAndroid(param);
            }
            ajaxJson.setObj(list);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("true");
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }

    @Override
    public JobSelectorWrapper searchAllType(HttpServletRequest request) {
        JobSelectorWrapper wrapper = new JobSelectorWrapper();
        wrapper.setStatus(true);
        wrapper.setFlag(false);
        //获取所有流程分类   目录
        List<FlowSort> allDatas = flowSortMapper.selectAllFsAdmin();

        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");

        for (FlowSort flowSort : allDatas) {//目录下有几个设计的流程或目录
            Integer flowCounts = flowSortMapper.countAllFs(flowSort.getSortId());
            flowSort.setFlowcounts(flowCounts);
        }
        List<FlowSort> authdatasSort = searchDatasAuthFlow(allDatas, 0, allDatas, sqlType);
        if (authdatasSort != null && authdatasSort.size() > 0) {
            wrapper.setFlag(true);
            wrapper.setMsg("获取成功");
            wrapper.setDatas(authdatasSort);
        } else {
            wrapper.setFlag(false);
            wrapper.setMsg("没有数据");
        }

        return wrapper;
    }


    private List<FlowSort> searchDatasAuthFlow(List<FlowSort> authdatas, Integer sortIda, List<FlowSort> alldata, String sqlType) {
        if (authdatas == null) return null;
        List<FlowSort> datas = new ArrayList<FlowSort>();
        //遍历权限获取
        for (FlowSort sort : authdatas) {
            if (sort != null) {
                //统计符合条件的
                List<FlowSort> authdatass = new ArrayList<FlowSort>();
                //流程分类不是一级分类

                if (sort.getSortParent() != 0) {
                    int checkRes = 0;
                    for (FlowSort need : authdatas) {//查询是不是都为一级分类
                        if (need.getSortId() != sort.getSortParent()) {
                            checkRes++;
                        }
                    }
                    //全部为一级分类
                    if (checkRes == authdatas.size()) {
                        authdatass.addAll(authdatas);
                        for (FlowSort all : alldata) {
                            if (all.getSortId() == sort.getSortParent()) {
                              /*  List<FlowTypeModel> list = flowTypeModelMapper.selectByFlowType(all.getSortId());
                                all.setFlowTypeModels(list);*/
                                authdatass.add(all);
                            }
                        }
                    }
                }
                if (authdatass.size() > 0) {
                    if (sort.getSortParent() == sortIda) {
                        List<FlowTypeModel> list = this.serchChildFlowType(sort.getSortId(), sqlType);
                        if (list!=null&&list.size()>0){
                            sort.setFlowTypeModels(list);
                            sort.setChilds(searchDatasAuthFlow(authdatass, sort.getSortId(), alldata, sqlType));
                            datas.add(sort);
                        }

                    }
                } else {
                    if (sort.getSortParent() == sortIda) {
                        List<FlowTypeModel> list = this.serchChildFlowType(sort.getSortId(), sqlType);
                        if (list!=null&&list.size()>0){
                            sort.setFlowTypeModels(list);
                            sort.setChilds(searchDatasAuthFlow(authdatas, sort.getSortId(), alldata, sqlType));
                            datas.add(sort);
                        }
                    }
                }

            }
        }
        return datas;
    }


    public JobSelectorWrapper selectFrom(HttpServletRequest request) {
        JobSelectorWrapper wrapper = new JobSelectorWrapper();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Integer deptId = null;
        if (users.getUserId() != null) {
            deptId = users.getDeptId();
        }
        List<FormSort> nosortDatas = new ArrayList<FormSort>();
        if (users.getUserId().trim().equals("admin")) {
            nosortDatas = sortMapper.selectAllByAdmin();
        } else {
            nosortDatas = sortMapper.selectAllFormSort(deptId);
        }

        Integer noform = sortMapper.selectNoformSort(deptId);
        List<FormSort> resultdatas = new ArrayList<FormSort>();
        FormSort formSort = new FormSort();
        formSort.setSortName("未定义");
        formSort.setFormcounts(noform);
        formSort.setHaveChild("0");
        formSort.setSortNo(0);
        resultdatas.add(formSort);
        List<FormSort> datasMap = this.sortDatas(nosortDatas, 0);
        resultdatas.addAll(datasMap);
        wrapper.setDatas(resultdatas);
        wrapper.setFlag(true);
        wrapper.setStatus(true);
        wrapper.setMsg("获取数据成功");
        return wrapper;


    }

    private List<FormSort> sortDatas(List<FormSort> nosortDatas, Integer sortIda) {
        if (nosortDatas == null) return null;
        List<FormSort> datas = new ArrayList<FormSort>();
        for (FormSort sort : nosortDatas) {
            if (sort != null) {
                if (sort.getSortParent() == sortIda) {
                    sort.setChilds(sortDatas(nosortDatas, sort.getSortId()));
                    sort.setFlowFormTypes(flowFormTypeMapper.selectForm(sort.getSortId()));
                    datas.add(sort);
                }
            }
        }
        return datas;
    }

    @Override
    public ToJson<FlowTypeModel> flowAuthOrSearchCommonWork(HttpServletRequest request) {
        Map<String, Object> param = new HashMap<String, Object>();
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (user.getUid() == null) {
            toJson.setFlag(1);
            toJson.setMsg("无法获取用户信息");
            return toJson;
        }
        String privOther = user.getUserPrivOther() == null ? "" : user.getUserPrivOther();//辅助角色
        String privIds[] = StringUtils.checkNull(privOther) ? null : privOther.split(",");
        String deptOther = user.getDeptIdOther() == null ? "" : user.getDeptIdOther();//辅助部门
        String deptIds[] = StringUtils.checkNull(deptOther) ? null : deptOther.split(",");
        param.put("user", user.getUserId() == null ? "" : user.getUserId());
        param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
        param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());

        // 查询单个流程是否有新建权限
        String flowId = request.getParameter("flowId");
        if (!StringUtils.checkNull(flowId)) {
            param.put("flowId", flowId);
        }

        if (privIds != null && privIds.length > 0) {
            param.put("privIds", privIds);
        }
        if (deptIds != null && deptIds.length > 0) {
            param.put("deptIds", deptIds);
        }
        List<FlowTypeModel> datas = flowTypeModelMapper.selectFlowAuthOrSearchCommonWork(param);
       /* if (user.getUserId() != null && user.getUserId().trim().equals("admin")) {
            datas = flowTypeModelMapper.selectFlowAuthOrSearchCommonWorkAdmin(param);
        }*/
        if (datas != null && datas.size() > 0) {
            toJson.setFlag(0);
            toJson.setMsg("成功");
            toJson.setObj(datas);
        } else {
            toJson.setFlag(1);
            toJson.setMsg("没有数据！");
        }
        return toJson;
    }


    public TemplateModuleMapper getTemplateModuleMapper() {
        return templateModuleMapper;
    }

    public void setTemplateModuleMapper(TemplateModuleMapper templateModuleMapper) {
        this.templateModuleMapper = templateModuleMapper;
    }

    @Override
    public ToJson flowClone(HttpServletRequest request) {
        ToJson<FlowTypeModel> toJson = new ToJson<FlowTypeModel>(1, "error");
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
        try {
            StringBuffer attachId = new StringBuffer();//流程说明附件id
            StringBuffer attachName = new StringBuffer();//流程说明附件name
            String flowId = request.getParameter("flowId");//当前流程flowid
            String flowName = request.getParameter("flowName");//复制后的文件名
            String[] ids = request.getParameter("ids").split(",");//权限
            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(Integer.parseInt(flowId));
            flowTypeModel.setFlowName(flowName);
            flowTypeModel.setFlowId(null);
            //复制流程说明附件
            if (!StringUtils.checkNull(flowTypeModel.getAttachmentId()) && !StringUtils.checkNull(flowTypeModel.getAttachmentName())) {
                List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(flowTypeModel.getAttachmentName(), flowTypeModel.getAttachmentId(), sqlType, "document");
                List<Attachment> attachments1 = fileUploadUtil.cppyFiles(attachments, sqlType, "workflow");
                for (Attachment attachment : attachments1) {//上传至附件表
                    enclosureService.saveAttachment(attachment);
                }
                Object[] o = FileUploadUtil.reAttachment(attachments1);   //返回附件信息
                flowTypeModel.setAttachmentId(o[0].toString());
                flowTypeModel.setAttachmentName(o[1].toString());
            }
            ToJson<FlowTypeModel> flowTypeModelcopy = this.saveFlow(flowTypeModel);
            Integer flowIdnew = ((FlowTypeModel) flowTypeModelcopy.getObject()).getFlowId();//复制后的flowid
            if (Arrays.asList(ids).contains("1")) {//流程步骤
                List<FlowProcess> FlowProcess = flowProcessMapper.findFlowId(Integer.parseInt(flowId));
                for (FlowProcess flow : FlowProcess) {
                    if (!Arrays.asList(ids).contains("2")) {//经办权限
                        flow.setPrcsUser(null);
                        flow.setPrcsDept(null);
                        flow.setPrcsPriv(null);
                    }
                    flow.setFlowId(flowIdnew);
                    flowProcessMapper.insert(flow);
                }
            }
            if (Arrays.asList(ids).contains("3")) {//流程权限
                List<FlowPrivWithBLOBs> flowPrivWithBLOBs = flowPrivMapper.queryByFlowId(Integer.parseInt(flowId));
                for (FlowPrivWithBLOBs flowPriv : flowPrivWithBLOBs
                ) {
                    flowPriv.setId(null);
                    flowPriv.setFlowId(flowIdnew);
                    flowPrivMapper.insertSelective(flowPriv);
                }
            }
            if (Arrays.asList(ids).contains("4")) {//关联流程
                List<FlowRelation> flowRelations = flowAssociationSetMapper.queryFlowAssociationSet(Integer.parseInt(flowId));
                for (FlowRelation flowRelation : flowRelations
                ) {
                    Map map = new HashMap();
                    map.put("flowId", flowIdnew);
                    map.put("flowRefNo", flowRelation.getFlowRefNo());
                    map.put("flowRelName", flowRelation.getFlowRelName());
                    map.put("relationType", flowRelation.getRelationType());
                    map.put("relationFlowId", flowRelation.getRelationFlowId());
                    map.put("relationStatus", flowRelation.getRelationStatus());
                    map.put("flowRange", flowRelation.getFlowRange());
                    map.put("timeRange", flowRelation.getTimeRange());
                    map.put("dataDirection", flowRelation.getDataDirection());
                    map.put("flowRelDesc", flowRelation.getFlowRelDesc());
                    map.put("mapping", flowRelation.getMapping());
                    map.put("mappingDesc", flowRelation.getMappingDesc());
                    flowAssociationSetMapper.newModelAssociationSet(map);
                }
            }
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            L.e("FlowTypeServiceImpl selAllType:" + e);
        }
        return toJson;
    }

    @Override
    public ToJson getAttachment(HttpServletRequest request) {
        ToJson<FlowDetailInfo> ret = new ToJson<FlowDetailInfo>();
        String flowId = request.getParameter("flowId");
        FlowDetailInfo attachment = flowTypeModelMapper.getAttachment(Integer.parseInt(flowId));
        if (!StringUtils.checkNull(attachment.getAttachmentId())) {//返回的附件信息
            attachment.setAttachmentList(GetAttachmentListUtil.returnAttachment(attachment.getAttachmentName(), attachment.getAttachmentId(), "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_WORKFLOW));
        }
        ret.setObject(attachment);
        ret.setFlag(0);
        ret.setMsg("成功");

        return ret;
    }

    //按照年份查询数据（流程门户显示）
    @Override
    public ToJson<FlowTypeModel> flowData(HttpServletRequest request, Integer flag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        ToJson json = new ToJson();
        Map<String, Object> map2 = new HashMap<>();
        List<FlowTypeModel> FlowTypeModels = this.flowAuthOrSearchCommonWork(request).getObj();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        for (int i = 0; i < 5; i++) {
            Map<String, Object> map = new HashMap<>();
            FlowTypeModel flowTypeModel = FlowTypeModels.get(i);
            map.put("flowId", flowTypeModel.getFlowId());
            map.put("userId", user.getUserId());
            map.put("prcsTime", String.valueOf(year));

            List<Map<String, Object>> maps = new ArrayList<>();
            if (flag == 1) {
                maps = flowRunPrcsMapper.selectbyYear(map);
            } else if (flag == 2) {
                maps = flowRunPrcsMapper.selectCountByFlowId(map);
            }
            map2.put(flowTypeModel.getFlowName(), maps);
        }
        json.setFlag(0);
        json.setMsg("ok");
        json.setObject(map2);
        return json;
    }

    //流程设计中的查询配置
    @Override
    public ToJson<FlowTypeModel> flowTypequeryList(Integer flowId) {
        ToJson<FlowTypeModel> json = new ToJson();
        FlowTypeModel flowTypeModel = flowTypeModelMapper.flowTypequeryList(flowId);
        json.setObject(flowTypeModel);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }

    //流程设计中的查询配置
    @Override
    public ToJson updateQueryList(FlowTypeModel flowTypeModel) {
        ToJson<FlowTypeModel> json = new ToJson();
        flowTypeModelMapper.updateQueryList(flowTypeModel);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }

    //根据flowID串查询flowName串
    @Override
    public java.lang.String getFlowNames(java.lang.String ids) {
        if (StringUtils.checkNull(ids)) {
            return "";
        }

        if (",".equals(String.valueOf(ids.charAt(ids.length() - 1)))) {
            ids = ids.substring(0, ids.length() - 1);
        }

        return flowTypeModelMapper.getFlowNames(ids);
    }

    //根据flowId串查询flowRun集合
    @Override
    public List<FlowDetailInfo> getFlowTypeModelList(String ids, String flowName, String flowSotr) {
        if (StringUtils.checkNull(ids)) {
            return new ArrayList();
        }

        if (",".equals(String.valueOf(ids.charAt(ids.length() - 1)))) {
            ids = ids.substring(0, ids.length() - 1);
        }

        return flowTypeModelMapper.getFlowTypeModelList(ids, flowName, flowSotr);
    }


    @Override
    public AjaxJson checkWFNewPriv(Users user, Integer flowId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            user=usersService.getUsersByuserId(user.getUserId());
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("flowId",flowId);
            String privOther = user.getUserPrivOther() == null ? "" : user.getUserPrivOther();//辅助角色
            String privIds[] = StringUtils.checkNull(privOther) ? null : privOther.split(",");
            String deptOther = user.getDeptIdOther() == null ? "" : user.getDeptIdOther();//辅助部门
            String deptIds[] = StringUtils.checkNull(deptOther) ? null : deptOther.split(",");
            param.put("user", user.getUserId() == null ? "" : user.getUserId());
            param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
            param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());
            if (privIds != null && privIds.length > 0) {
                param.put("privIds", privIds);
            }
            if (deptIds != null && deptIds.length > 0) {
                param.put("deptIds", deptIds);
            }
            String flag = flowTypeModelMapper.checkWFNewPriv(param);
            if ("1".equals(flag)) {
                FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
                if (!StringUtils.checkNull(flowTypeModel.getNewType())&&flowTypeModel.getNewType().contains("1")){
                    ajaxJson.setMsg("OK");
                    ajaxJson.setFlag(true);
                }else{
                    ajaxJson.setMsg("false");
                    ajaxJson.setFlag(false);
                }
            } else {
                ajaxJson.setMsg("false");
                ajaxJson.setFlag(false);
            }

        } catch (Exception e) {
            ajaxJson.setMsg("false");
            ajaxJson.setFlag(false);
        }
        return ajaxJson;

    }
}